package cn.zzuli.springcloud.controller;

import cn.zzuli.commons.entity.CommonResult;
import cn.zzuli.commons.entity.Payment;
import cn.zzuli.springcloud.service.PaymentService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Date: 2020/12/26 13:51
 * @Author: 绯色下午茶
 * @Description:
 */
@RestController
@Slf4j
@RequestMapping("/consumer")
public class CircleBreakerController {
    public static final String SERVICE_URL="http://nacos-provider-payment";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/fallback/{id}")
    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "fallbackHandler")
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler")
    public CommonResult fallback(@PathVariable("id") Long id) throws IllegalAccessException {
        CommonResult result = restTemplate.getForObject(SERVICE_URL+"/provider/paymentSQL/"+id,CommonResult.class,id);

        if (id>7){
            throw new IllegalAccessException("非法参数异常******");
        }else if (result.getData()==null){
            throw new NullPointerException("该id没有对应数据，空指针异常");
        }
        return result;
    }

    public CommonResult<Payment> fallbackHandler(Long id, Throwable e) throws IllegalAccessException {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(444,"fallbackHandler,兜底的异常，异常内容是::"+ e.getMessage(),payment);
    }

    public CommonResult<Payment> blockHandler(Long id)  {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler,限流");
    }


    @Resource
    private PaymentService paymentService;


    @GetMapping("/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") long id){
        return paymentService.paymentSQL(id);
    }
}
